package cn.wolfcode.cloud.orderserver.controller;

import cn.wolfcode.cloud.orderserver.domain.Order;
import cn.wolfcode.cloud.orderserver.service.IOrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/orders")
@Slf4j
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping
    @HystrixCommand(fallbackMethod = "saveFail")
    public Order save(Long userId, Long productId, HttpServletRequest request) {

        log.info("订单服务 接受的参数:userId={},productId={}",userId,productId);
        //int i = 1 / 0;
        String token = request.getHeader("token");
        String cookie = request.getHeader("cookie");
        log.info("token={},cookie={}",token,cookie);
        Order order = orderService.save(userId, productId);
        log.info("订单服务 响应的参数:{}",order);
        return order;

    }

    public Order saveFail(Long userId, Long productId, HttpServletRequest request) {
        log.info("订单服务降级处理...");

        new Thread(() -> {
            String key = "NOTE_LIVECYCLE";

            if (!redisTemplate.hasKey(key)) {
                log.info("发送短信!");
                redisTemplate.opsForValue().set(key, "", 10, TimeUnit.SECONDS);
            } else {
                log.info("已经发送过短信!");
            }
        }).start();

        Order order = new Order();

        return order;

    }

}